// 使用 jQuery 获取元素
const $drawerToggleButton = $('#drawer-toggle');
const $drawer = $('#drawer');
const $drawerIcon = $('.drawer-icon');
const $cameraElement = $('#camera');
const $shutterButton = $('.shutter-button')


// 切换抽屉和图标旋转的函数
function toggleDrawer(action) {
    // 获取当前的状态
    const isOpen = $drawer.hasClass('open');

    if (action === 'open') {
        // 强制打开抽屉
        $drawer.addClass('open');
        $drawerIcon.css('transform', 'rotate(-90deg)'); // 打开时旋转图标
    } else if (action === 'close') {
        // 强制关闭抽屉
        $drawer.removeClass('open');
        $drawerIcon.css('transform', 'rotate(90deg)'); // 关闭时恢复图标旋转
    } else {
        // 默认情况，取反当前状态
        if (isOpen) {
            $drawer.removeClass('open');
            $drawerIcon.css('transform', 'rotate(90deg)');
        } else {
            $drawer.addClass('open');
            $drawerIcon.css('transform', 'rotate(-90deg)');
        }
    }
}

// 将代码封装在一个初始化函数中，只有调用时才执行
function setupDrawer() {
    // 为按钮添加点击事件监听器
    $drawerToggleButton.on('pointerdown', function () {
        toggleDrawer();
    });
    
    // 点击相机区域关闭抽屉
    if ($cameraElement.length) {
        $cameraElement.on('click', function () {
            // 如果抽屉打开，则关闭它
            if ($drawer.hasClass('open')) {
                toggleDrawer();
            }
        });
    }

    // 点击相机拍照关闭抽屉
    if ($shutterButton.length){
        $shutterButton.on('click',function(){
            // 如果抽屉打开，则关闭它
            if ($drawer.hasClass('open')) {
                toggleDrawer();
            }
        })
    }

    // 调整 image-gallery 的高度
    adjustImageGalleryHeight();
}

// 调整 image-gallery 图片列表 的高度
function adjustImageGalleryHeight() {
    // 三秒以确保浏览器加载完成
    setTimeout(() => {
        const $drawerContent = $('#drawer-content');
        const $drawerTitle = $('#drawer-title');
        const $imageGallery = $('#image-gallery');

        if ($drawerContent.length && $drawerTitle.length && $imageGallery.length) {
            const drawerContentHeight = $drawerContent.outerHeight();
            const drawerTitleHeight = $drawerTitle.outerHeight();

            // 计算剩余空间并设置 image-gallery 的高度
            const imageGalleryHeight = drawerContentHeight - drawerTitleHeight;
            $imageGallery.css('height', `${imageGalleryHeight}px`);

            // 打印相关值以便调试
            console.log(`drawerContentHeight: ${drawerContentHeight}`);
            console.log(`drawerTitleHeight: ${drawerTitleHeight}`);
            console.log(`设置 image-gallery 高度为: ${imageGalleryHeight}`);
        }
    }, 3000);
}

// 导出函数
export { setupDrawer, toggleDrawer };
